package com.nio;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * Desc: nio读写文件
 * @author: lisha 2018/7/27 11:02
 */
public class TestReadWrite {

    private static int len;

    /**
     * read
     * @param fileName
     * @return
     */
    public static ByteBuffer readFile(String fileName){
        try {
            RandomAccessFile file = new RandomAccessFile(fileName,"rw");
            len = (int) file.length();
            FileChannel channel = file.getChannel();
            MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, len);
            return buffer.get(new byte[(int) file.length()]);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 写文件
     * @param readFileName
     * @param writeFileName
     */
    public static void writeFile(String readFileName, String writeFileName){
        try {
            RandomAccessFile file = new RandomAccessFile(writeFileName, "rw");
            FileChannel channel = file.getChannel();
            ByteBuffer buffer = readFile(readFileName);

            MappedByteBuffer byteBuffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, len);
            long startTime = System.currentTimeMillis();
            for (int i = 0; i < len; i++) {
                byteBuffer.put(i, buffer.get(i));
            }

            byteBuffer.flip();
            long endTime = System.currentTimeMillis();
            System.out.println("写文件时间：" + (endTime - startTime));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String readFileName = "E:\\books.zip";
        String writeFileName = "E:\\books-copy.zip";

        for (int i = 1; i <= 10; i++) {
            System.out.println("第" + i + "次----");
            writeFile(readFileName, writeFileName);
        }
    }
}
